package com.yj.auto.plugin.lucene;

import java.util.List;

import org.quartz.JobExecutionContext;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.yj.auto.core.base.exception.AutoRuntimeException;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.web.system.model.Atta;
import com.yj.auto.core.web.system.service.AttaService;
import com.yj.auto.helper.AutoHelper;
import com.yj.auto.job.AutoJob;
import com.yj.auto.plugin.lucene.model.AutoIndexWriter;
import com.yj.auto.plugin.lucene.utils.LuceneUtil;

//全文检索索引生成
public class LuceneIndexBuildJob extends AutoJob {
	private static final Log logger = Log.getLog(LuceneIndexBuildJob.class);

	@Override
	public void run(JobExecutionContext context) {
		AttaService attaSrv = AutoHelper.getAttaService();
		QueryModel query = new QueryModel();
		query.put("lastId", LuceneUtil.getLastAttaId());
		// query.put("lastId", 0);
		query.put("extArray", LuceneUtil.INDEX_FILE_EXT);
		query.put("typeArray", LuceneUtil.INDEX_ATTA_TYPE);
		query.setOrderby("id");
		Integer tempId = null;
		int success = 0, failed = 0;
		AutoIndexWriter writer = null;
		try {
			writer = new AutoIndexWriter();
		} catch (Exception e) {
			throw new AutoRuntimeException("get index writer error", e);
		}
		try {
			while (true) {
				Page<Atta> page = attaSrv.paginate(query);
				List<Atta> list = page.getList();
				for (Atta model : list) {
					tempId = model.getId();
					try {
						LuceneUtil.addDocument(writer, model);
						success++;
					} catch (Exception e) {
						failed++;
						logger.error("add index error, atta json is " + model.toJson(), e);
					}
				}
				if (list.size() < page.getPageSize()) {// 所有文档检索完成
					if (null != tempId) {
						LuceneUtil.updateLastAttaId(tempId);
					}
					break;
				}
			}
		} finally {
			writer.release();
		}
		logger.info("build index,success=" + success + ",failed=" + failed);

	}

}
